package com.limetalks.servlet;

import java.io.IOException;

import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.limetalks.dao.UserDAO;
import com.limetalks.data.User;
import com.limetalks.util.GlobalStrings;


public class LoginServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
    
	private static UserDAO userDAO;
	
    public LoginServlet() {
    	super();
    	userDAO = new UserDAO(Persistence.createEntityManagerFactory(GlobalStrings.PERSISTENCE_UNIT_NAME));
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String login = request.getParameter("login");
		String password = request.getParameter("password");

		User user = userDAO.findByEmailPassword(login, password);
		
		boolean auth = (user != null);
		if(auth) {
			String location = request.getParameter("loc");
			request.getSession().setAttribute("user",user);
			response.sendRedirect(location);
		} else {
			//TODO: redirect to login page
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
